package com.goodlearning.gloriamobile.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.goodlearning.gloriamobile.R;
import com.goodlearning.gloriamobile.commons.Utils;
import com.goodlearning.gloriamobile.customview.ButtonGroup;
import com.goodlearning.gloriamobile.dto.GetSchListResultDto;
import com.goodlearning.gloriamobile.net.JsonRequestThread.INetSuccessCallback;
import com.goodlearning.gloriamobile.net.JsonServiceRequester;
import com.goodlearning.gloriamobile.net.JsonWrapper;

/**
 * 학사 일정 관련 Activity
 * 
 * @author rapty54
 * 
 */
public class AdministrationCheckSchedule extends BaseActivity {

	private int[] schBtnIdxs = { 
			 R.id.schedule_year_tab_Button_1
			,R.id.schedule_year_tab_Button_2
			,R.id.schedule_year_tab_Button_3 };
	
	ButtonGroup schBg;
	
	Button previousOfYear,secondYear,NextOfYear;
	
	int NeutralityOfDate,IncreaseOfDate,DecreaseOfDate,checkLifeCycleCount,monthCount,checkInit;
	
	String prevoiusYear,naturallyYear,nextYear;
	
	private LinearLayout detailLl,newTitleLl;
	
	View itemView;
	
	ArrayList<GetSchListResultDto> getSchListResultDtos;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.administration_check_the_schedule_layout);
		init();
	}

	public void init() {
		
		baseTitleLeftBtn.setVisibility(View.VISIBLE);
		baseTitleLeftBtn.setText(R.string.btn_char1_shift_1);
		baseTitleLeftBtn.setTextColor(getResources().getColor(R.color.administration_fourth_text_change));
		baseTitleLeftBtn.setTextSize(20.0f);

		detailLl = (LinearLayout) findViewById(R.id.adminstration_scd_plan_planresult_detail_LinearLayout);
		
		previousOfYear=(Button)findViewById(R.id.schedule_year_tab_Button_1);
		secondYear=(Button)findViewById(R.id.schedule_year_tab_Button_2);
		NextOfYear=(Button)findViewById(R.id.schedule_year_tab_Button_3);
		
		DecreaseOfDate=NeutralityOfDate-1;
		IncreaseOfDate=NeutralityOfDate+1;
		
		prevoiusYear=Utils.getYearAddRemove(DecreaseOfDate, 0);
		naturallyYear=Utils.getYearAddRemove(NeutralityOfDate, 0);
		nextYear=Utils.getYearAddRemove(IncreaseOfDate, 0);
		

		previousOfYear.setText(prevoiusYear);
		secondYear.setText(naturallyYear);
		NextOfYear.setText(nextYear);
		
		baseTitleTv.setText("학사일정");
		baseTitleRightBtn.setVisibility(View.INVISIBLE);
		
		/**
		 * TabButton 정의 (Tab 에 대한 Listen)
		 */
		
		schBg = new ButtonGroup(this, schBtnIdxs,true,true);
		schBg.setOnCheckedChangeListener(new ButtonGroup.OnCheckedChangeListener() {

			@Override
			public void onCheckedChange(Button button) {
				Utils.log("Button:" + "[" + button.getId() + "]" + "||"+ "Button Idx:" + "[" + schBg.getCheckedButtonIdx()+ "]");
				
				switch (schBg.getCheckedButtonIdx()) {
				case 0:
//					detailLl.removeAllViews();
					requestSchedule(prevoiusYear);
					break;
				case 1:
//					detailLl.removeAllViews();
					Utils.log("==========="+"["+1+"]");
					requestSchedule(naturallyYear);
					break;
				case 2:
//					detailLl.removeAllViews();
					requestSchedule(nextYear);
					break;
				default:
					break;
				
				}
			}
		});
	}
	/**
	 * 초기기동 설정 제일 이전에 년도 결과 값을 가져와서 초기기동 후 한번만 실행한다.
	 * 추가적으로 실행된으로써 여러번 반복 작업을 안함
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		checkLifeCycleCount++;
		
		if(checkLifeCycleCount==1){
			requestSchedule(naturallyYear);
		}
		
	}
	/**
	 * UI 갱신 동작 부분 하단 함수에서 일괄 처리한다.
	 * UI 를 새로 갱신하는 부분까지 모두 묶인 함수 정의 현재 하나의 함수로 모든 처리를 완료한다.
	 * @param searchYear
	 */
	public void requestSchedule(String searchYear){
		JsonServiceRequester.requestGetInProgressScheduleList(AdministrationCheckSchedule.this, searchYear, new INetSuccessCallback() {
			
			@Override
			public void sendCallback(JsonWrapper jsonWrapper) {
				
				JSONArray jsonArray=jsonWrapper.getRootArray();
				
				getSchListResultDtos=new ArrayList<GetSchListResultDto>();
				
				for(int i=0;i<jsonArray.size();i++){
					
					JSONObject jsonObject=(JSONObject)jsonArray.get(i);
					
					GetSchListResultDto getSchListResultDto=new GetSchListResultDto();
					
					getSchListResultDto.sethMonth(Utils.convertObjToString(jsonObject.get("hMonth")));
					getSchListResultDto.setIljung(Utils.convertObjToString(jsonObject.get("iljeong")));
					
					getSchListResultDtos.add(getSchListResultDto);
				}
				
				    setVisibleEmptyAreaOtherType(jsonArray.size()==0);
				    detailLl.removeAllViews();
				    showDayOfPlan(getSchListResultDtos, 1, 12);
				}
		});
	}
	
	public void showDayOfPlan(ArrayList<GetSchListResultDto> getSchListResultDtos,int currentday,int totalDay){
		
		Map<String, LinearLayout> createTitleInfoMap = new HashMap<String, LinearLayout>();
		
		for(int i=currentday;i<=totalDay;i++){
			
			newTitleLl = createTitleInfoMap.get(i);
			newTitleLl = (LinearLayout) LayoutInflater.from(AdministrationCheckSchedule.this).inflate(R.layout.administration_planresult_detail_title_row, null);
			
			createTitleInfoMap.put(String.valueOf(i), newTitleLl);
			
			((TextView) newTitleLl.findViewById(R.id.administration_plan_planresult_detail_title_row_title_TextView)).setText(String.valueOf(i)+"월");
			
			detailLl.addView(newTitleLl, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			
			Utils.log("Month:"+i);
			
			for(int j=0;j<getSchListResultDtos.size();j++){
				
				if(getSchListResultDtos.get(j).gethMonth().equals(String.valueOf(i))){
					
					itemView = LayoutInflater.from(AdministrationCheckSchedule.this).inflate(R.layout.administration_planresult_detail_item_row_textview, null);
					
					((TextView) itemView.findViewById(R.id.administration_plan_planresult_detail_item_row_0_TextView)).setText(getSchListResultDtos.get(j).getIljung());
					
					newTitleLl.addView(itemView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
					
				}else if(getSchListResultDtos.get(j).getIljung().equals("")){
					
					Utils.log("====================일정이 없는 달=============");
				}
				
			}
			
		}
	}
}
